package com.myapp;

import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class DataSourceFactory {

    private static int i = 0;

    public static DataSource getDataSource() {
        DataSource dataSource = new EmbeddedDatabaseBuilder()
                .setName("db" + (i++))
                .setType(EmbeddedDatabaseType.H2)
                .addScript("schema.sql")
                .build();
        initData(dataSource);

        return dataSource;

//        P6DataSource retDatasource = new P6DataSource(dataSource);
//        return retDatasource;
    }

    public static void initData(DataSource dataSource) {
        for (int i = 1; i <= 2; i++) {
            try (Connection connection = dataSource.getConnection()) {
                String userName = "admin" + i;

                String sql = "INSERT INTO `t_user`(`id`,`username`,`state`,`isdel`,`remark`,`add_time`,`money`,`left_money`) VALUES ("+i+",'"+userName+"',0,0,'批量修改备注','2017-02-21 10:37:44','101.10',22.1);";
                Statement statement = connection.createStatement();
                statement.execute(sql);
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
